//
//  ContentView.swift
//  replaykit
//
//  Created by zhang on 2025/7/31.
//

import SwiftUI

struct ContentView: View {
    @StateObject private var cameraManager = CameraManager()
    @State private var showCameraView = false
    
    var body: some View {
        ZStack {
            // 相机视图 - 全屏显示
            if showCameraView {
                CameraView(cameraManager: cameraManager)
                    .ignoresSafeArea()
            } else {
                // 占位视图
                Color.black
                    .ignoresSafeArea()
            }
            
            // 状态指示器
            VStack {
                Spacer()
                HStack {
                    Spacer()
                    if let errorMessage = cameraManager.errorMessage {
                        Text(errorMessage)
                            .foregroundColor(.white)
                            .padding()
                            .background(Color.red.opacity(0.8))
                            .cornerRadius(8)
                            .padding()
                    } else if cameraManager.isCameraReady {
                        Text("相机运行中")
                            .foregroundColor(.white)
                            .padding()
                            .background(Color.black.opacity(0.5))
                            .cornerRadius(8)
                            .padding()
                    } else {
                        Text("正在初始化相机...")
                            .foregroundColor(.white)
                            .padding()
                            .background(Color.black.opacity(0.5))
                            .cornerRadius(8)
                            .padding()
                    }
                }
            }
        }
        .onAppear {
            print("ContentView: 视图出现，开始设置相机")
            cameraManager.setupCamera()
            
            // 延迟启动相机会话，确保配置完成
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                cameraManager.startSession()
                
                // 再延迟显示相机视图，确保会话已启动
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    showCameraView = true
                    print("ContentView: 显示相机视图")
                }
            }
        }
        .onDisappear {
            print("ContentView: 视图消失，停止相机")
            cameraManager.stopSession()
        }
    }
}

#Preview {
    ContentView()
}
